package com.xoa.service.hr;

import com.xoa.dao.common.HrCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.duties.DutiesManagementMapper;
import com.xoa.dao.hr.HrTransferMapper;
import com.xoa.dao.users.UserDeptOrderMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.HrCode;
import com.xoa.model.common.HrCodeExample;
import com.xoa.model.duties.UserPost;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.hr.HrTransfer;
import com.xoa.model.hr.HrTransferWithBLOBs;
import com.xoa.model.hr.HrphotoWithBLOBs;
import com.xoa.model.users.UserDeptOrder;
import com.xoa.model.users.Users;
import com.xoa.service.users.impl.UsersServiceImpl;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 左春晖    人事调动  增删改查 导入 导出
 * @date 2018/7/12 10:01
 * @desc
 */
@Service
public class HrTransferService {


    @Resource
    HrTransferMapper hrTransferMapper;

    @Resource
    DepartmentMapper departmentMapper;

    @Resource
    UsersMapper usersMapper;

    @Resource
    HrCodeMapper hrCodeMapper;

    @Resource
    DutiesManagementMapper dutiesManagementMapper;

    @Resource
    UserDeptOrderMapper userDeptOrderMapper;

    @Resource
    UsersServiceImpl usersService;


    /**
     * 添加
     */
    public ToJson addHrTransfer (HttpServletRequest request,HrTransferWithBLOBs hrTransferWithBLOBs){
            ToJson json = new ToJson();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        //创建者用户名
        hrTransferWithBLOBs.setCreateUserId(user.getUserId());
        //创建者部门编号
        hrTransferWithBLOBs.setCreateDeptId(user.getDeptId());
        //日期转换为 yyyy-dd-MM
        String transferPerson = hrTransferWithBLOBs.getTransferPerson();
        //员工姓名
        if (transferPerson.contains(",")) {
            String substring = transferPerson.substring(0, transferPerson.length() - 1);
            hrTransferWithBLOBs.setTransferPerson(substring);
        }
        //批示
        if(StringUtils.checkNull(hrTransferWithBLOBs.getDespacho())){
            hrTransferWithBLOBs.setDespacho("");
        }
        //调动手续办理
        if (StringUtils.checkNull(hrTransferWithBLOBs.getMaterialsCondition())){
            hrTransferWithBLOBs.setMaterialsCondition("");
        }
        //附件名称
        if (StringUtils.checkNull(hrTransferWithBLOBs.getAttachmentName())){
            hrTransferWithBLOBs.setAttachmentName("");
        }
        //附件ID
        if (StringUtils.checkNull(hrTransferWithBLOBs.getAttachmentId())){
            hrTransferWithBLOBs.setAttachmentId("");
        }
        //备注
        if (StringUtils.checkNull(hrTransferWithBLOBs.getRemark())){
            hrTransferWithBLOBs.setRemark("");
        }
        //经办人
        if (StringUtils.checkNull(hrTransferWithBLOBs.getResponsiblePerson())){
            hrTransferWithBLOBs.setResponsiblePerson("");
        }
        //调动类别
        if (StringUtils.checkNull(hrTransferWithBLOBs.getTransferType())){
            hrTransferWithBLOBs.setTransferType("");
        }
        //调动原因
        if (StringUtils.checkNull(hrTransferWithBLOBs.getTranReason())){
            hrTransferWithBLOBs.setTranReason("");
        }
        //调动前单位
        if (StringUtils.checkNull(hrTransferWithBLOBs.getTranCompanyBefore())){
            hrTransferWithBLOBs.setTranCompanyBefore(" ");
        }
        //调动前部门
        if (StringUtils.checkNull(hrTransferWithBLOBs.getTranDeptBefore())){
            hrTransferWithBLOBs.setTranDeptBefore(" ");
        }
        //调动前职务
        if (StringUtils.checkNull(hrTransferWithBLOBs.getTranPositionBefore())){
            hrTransferWithBLOBs.setTranPositionBefore(" ");
        }
        //调动后单位
        if (StringUtils.checkNull(hrTransferWithBLOBs.getTranCompanyAfter())){
            hrTransferWithBLOBs.setTranCompanyAfter(" ");
        }
        //调动后部门
        if (StringUtils.checkNull(hrTransferWithBLOBs.getTranDeptAfter())){
            hrTransferWithBLOBs.setTranDeptAfter(" ");
        }
        //调动后职务
        if (StringUtils.checkNull(hrTransferWithBLOBs.getTranPositionAfter())){
            hrTransferWithBLOBs.setTranPositionAfter(" ");
        }
        //添加日期转换
        if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferDates())){
            hrTransferWithBLOBs.setTransferDate(DateFormat.getDates(hrTransferWithBLOBs.getTransferDates()));
        }
        //添加日期转换
        if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferEffectiveDates())){
            hrTransferWithBLOBs.setTransferEffectiveDate(DateFormat.getDates(hrTransferWithBLOBs.getTransferEffectiveDates()));
        }

        //登记时间
        hrTransferWithBLOBs.setAddTime(new Date());
        //最后修改时间
        hrTransferWithBLOBs.setLastUpdateTime(new Date());

        int temp = hrTransferMapper.insertSelective(hrTransferWithBLOBs);
        if (temp > 0) {
            if(!hrTransferWithBLOBs.getTranDeptBefore().equals(hrTransferWithBLOBs.getTranDeptAfter()) || !hrTransferWithBLOBs.getTranPositionAfter().equals(hrTransferWithBLOBs.getTranPositionBefore())){
                String userIdArr[] = hrTransferWithBLOBs.getTransferPerson().split(",");
                Users  userSingle = new Users();
                for(int i = 0;i < userIdArr.length;i ++){
                    String deptZhu = "";
                    //获取users数据
                    Users users = usersMapper.getUserId(userIdArr[i]);
                    int deptone = Integer.parseInt(hrTransferWithBLOBs.getTranDeptBefore().replaceAll(",",""));
                    if(deptone == users.getDeptId()){
                        userSingle.setDeptId(Integer.parseInt(hrTransferWithBLOBs.getTranDeptAfter().replaceAll(",","")));
                        deptZhu="1";
                    }else{
                        userSingle.setDeptIdOther(hrTransferWithBLOBs.getTranDeptAfter());
                    }
                    //获取userpost表的数据
                    UserPost userPost = dutiesManagementMapper.getUserPostByPostName(hrTransferWithBLOBs.getTranPositionAfter());
                    if(userPost != null){
                        userSingle.setPostId(userPost.getPostId());
                    }
                    userSingle.setUserId(users.getUserId());
                    usersMapper.updateByUserId(userSingle);

                    if ("1".equals(deptZhu)){
                        try {// 更新部门人员排序表   只考虑主部门
                            Users usersByuserId = usersMapper.findUsersByuserId(hrTransferWithBLOBs.getTransferPerson());
                            UserDeptOrder userDeptOrder1 = userDeptOrderMapper.selectUserAndDept(usersByuserId.getUserId(), Integer.parseInt(hrTransferWithBLOBs.getTranDeptBefore()));
                            userDeptOrder1.setDeptId(Integer.parseInt(hrTransferWithBLOBs.getTranDeptAfter().split(",")[0]));
                            userDeptOrder1.setPostId(Integer.parseInt(hrTransferWithBLOBs.getTranPositionAfter()));
                            userDeptOrderMapper.updateByPrimaryKeySelective(userDeptOrder1);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                }
            }
            json.setTurn(true);
            json.setFlag(0);
            json.setMsg("添加成功");
        } else {
            json.setFlag(1);
            json.setTurn(false);
            json.setMsg("添加失败");
        }
        return json ;
    }
    /**
     * 删除   前台传字符串   有传单个也有传多个。
     */
    public ToJson deleteHrTransfer(String[] ids){
       ToJson json = new ToJson();
        int temp =hrTransferMapper.deleteByPrimaryKeys(ids);
        if (temp > 0) {
            json.setTurn(true);
            json.setFlag(0);
            json.setMsg("删除成功");
        } else {
            json.setTurn(false);
            json.setFlag(1);
            json.setMsg("删除失败");
        }
        return json;
    }

    /**
     * 修改
     */
    public ToJson upHrTransfer( HrTransferWithBLOBs hrTransferWithBLOBs){
        ToJson json = new ToJson();
        int temp = hrTransferMapper.updateByPrimaryKeySelective(hrTransferWithBLOBs);
        if (temp > 0) {
            if(hrTransferWithBLOBs.getTranDeptAfter() != null || hrTransferWithBLOBs.getTranPositionAfter() != null){
                String userIdArr[] = hrTransferWithBLOBs.getTransferPerson().split(",");
                Users  userSingle = new Users();
                for(int i = 0;i < userIdArr.length;i ++){
                    //获取users数据
                    Users users = usersMapper.getUserId(userIdArr[i]);
                    int deptone = Integer.parseInt(hrTransferWithBLOBs.getTranDeptBefore().replaceAll(",",""));
                    if(deptone == users.getDeptId()){
                        userSingle.setDeptId(Integer.parseInt(hrTransferWithBLOBs.getTranDeptAfter().replaceAll(",","")));
                    }else{
                        userSingle.setDeptIdOther(hrTransferWithBLOBs.getTranDeptAfter());
                    }
                 /*   //获取userpost表的数据
                    UserPost userPost = dutiesManagementMapper.getUserPostByPostName(hrTransferWithBLOBs.getTranPositionAfter());
                    if(userPost != null){
                       }*/
                 if(!"".equals(hrTransferWithBLOBs.getTranPositionAfter())){
                     userSingle.setPostId(Integer.valueOf(hrTransferWithBLOBs.getTranPositionAfter()));
                 }
                    userSingle.setUserId(users.getUserId());
                    usersMapper.updateUserByUserId(userSingle);
                }
            }
            json.setTurn(true);
            json.setFlag(0);
            json.setMsg("修改成功");
        } else {
            json.setTurn(false);
            json.setFlag(1);
            json.setMsg("修改失败");
        }
        return json;
    }

    /**
     * 查询  导出   基本查询用   传值不传都可以
     */
    public ToJson<HrTransferWithBLOBs> selectHrTransfer(HttpServletResponse response,HttpServletRequest request , HrTransferWithBLOBs hrTransferWithBLOBs,Integer page, Integer pageSize, boolean useFlag, String export) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException {
       ToJson json = new ToJson();
        String[] dept ;
        String deptBefore="";
        String[] dept1 ;
        String deptBefore1="";
        List<HrTransferWithBLOBs> list = new ArrayList<>();
        Map<String,Object> maps= new HashMap<>();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        maps.put("page", pageParams);
        if(hrTransferWithBLOBs.getTransferId()!=null){
            maps.put("transferId",hrTransferWithBLOBs.getTransferId());
        }
        if(!StringUtils.checkNull(hrTransferWithBLOBs.getTransferPerson())){
            if (hrTransferWithBLOBs.getTransferPerson().contains(",")) {
            String substring = hrTransferWithBLOBs.getTransferPerson().substring(0, hrTransferWithBLOBs.getTransferPerson().length() - 1);
                maps.put("transferPerson",substring);
            }
        }
        if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferType())){
            maps.put("transferType",hrTransferWithBLOBs.getTransferType());
        }
        if (!StringUtils.checkNull(hrTransferWithBLOBs.getTranReason())){
            maps.put("tranReason",hrTransferWithBLOBs.getTranReason());
        }
       // 调动生效日期
        if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferEffectiveDateStart())){
            maps.put("transferEffectiveDateStart",hrTransferWithBLOBs.getTransferEffectiveDateStart());
        }
        //调动生效日期
        if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferEffectiveDateEnd())){
            maps.put("transferEffectiveDateEnd",hrTransferWithBLOBs.getTransferEffectiveDateEnd());
        }
        //调动日期
        if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferDateStart())){
            maps.put("transferDateStart",hrTransferWithBLOBs.getTransferDateStart());
        }
        //调动日期
        if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferDateEnd())){
            maps.put("transferDateEnd",hrTransferWithBLOBs.getTransferDateEnd());
        }
        if (hrTransferWithBLOBs.getTransferPerson()!=null&& hrTransferWithBLOBs.getTransferPerson()!=""){
            //判断用户是否为空并转化字符串
            if(!StringUtils.checkNull(hrTransferWithBLOBs.getTransferPerson().toString())){
                String fromIds = hrTransferWithBLOBs.getTransferPerson().toString();
                String[] substring = fromIds.split(",");//分割
                maps.put("transferPerson",substring);
            }
        }

        list = hrTransferMapper.Allselect(maps);
        //处理姓名
        for (HrTransferWithBLOBs  hr :list){
            String transferPerson = hr.getTransferPerson();
            //员工姓名
            if (transferPerson.contains(",")) {
                String substring = transferPerson.substring(0, transferPerson.length() - 1);
                hr.setTransferPerson(substring);
            }
            String username = usersMapper.getUsernameByUserId(hr.getTransferPerson());
            hr.setTransferPerson(username);
            //处理部门
            if(!StringUtils.checkNull(hr.getTranDeptBefore())){
                dept = hr.getTranDeptBefore().split(",");
                for(String  hr1 : dept){
                    String deptName=departmentMapper.getDeptNameById(Integer.parseInt(hr1));
                    deptBefore += deptName+",";
                }
                hr.setTranDeptBefore(deptBefore);
            }
            if(!StringUtils.checkNull(hr.getTranDeptAfter())){
                dept1 = hr.getTranDeptAfter().split(",");
                for(String  hr2 : dept1){
                    String deptName=departmentMapper.getDeptNameById(Integer.parseInt(hr2));
                    deptBefore1 += deptName+",";
                }
                hr.setTranDeptAfter(deptBefore1);
            }
            switch(hr.getTransferType()){
                case"1":
                    hr.setTransferType("晋升");
                    break;
                case "2":
                    hr.setTransferType("平调");
                    break;
                case"3":
                    hr.setTransferType("降级");
                    break;
                case "4":
                    hr.setTransferType("其他");
                    break;
            }
        }
        //附件處理
        List<Attachment> attachmentList=new ArrayList<Attachment>();
        if(hrTransferWithBLOBs.getAttachmentName()!=null&&!"".equals(hrTransferWithBLOBs.getAttachmentName())){
            attachmentList= GetAttachmentListUtil.returnAttachment(hrTransferWithBLOBs.getAttachmentName(),hrTransferWithBLOBs.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.INCENTIVE);
        }
        hrTransferWithBLOBs.setAttachmentList(attachmentList);
        json.setMsg("OK");
        json.setFlag(0);
        json.setTurn(true);
        json.setObj(list);
        json.setTotleNum(pageParams.getTotal());
        //导出
        if("1".equals(export)){
            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("人事调动", 13);
            String[] secondTitles = {"调动人员", "调动类型","调动日期","调动生效日期","调动前单位","调动后单位","调动前部门","调动后部门","调动前职务","调动后职务","调动手续办理","调动原因","备注"};
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
            String[] beanProperty = {"transferPerson","transferType","transferDate","transferEffectiveDate","tranCompanyBefore","tranCompanyAfter","tranDeptBefore","tranDeptAfter","tranPositionBefore","tranPositionAfter","materialsCondition","tranReason","remark"};
            HSSFWorkbook workbook = null;
            workbook = ExcelUtil.exportExcelData(workbook2, list, beanProperty);
            OutputStream out = response.getOutputStream();
            String filename = "人事调动.xls";
            filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
        }
        return json;
    }

    /**
     * 通过ID查找信息
     */
    public ToJson<HrTransferWithBLOBs> selectBytransferId(HttpServletRequest request, Integer transferId) {
        ToJson<HrTransferWithBLOBs> json = new ToJson<HrTransferWithBLOBs>(1,"err");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);

        String[] dept ;
        String deptBefore="";
        String deptBefores="";
        try{
            //根据ID查找下对应的用户
            HrTransferWithBLOBs hrTransferWithBLOBs = hrTransferMapper.selectByPrimaryKey(transferId);
            if(hrTransferWithBLOBs.getTranDeptBefore() != null || hrTransferWithBLOBs.getTranDeptAfter() != null){
                hrTransferWithBLOBs.setDeptIdBefore(hrTransferWithBLOBs.getTranDeptBefore());
                hrTransferWithBLOBs.setDeptIdAfter(hrTransferWithBLOBs.getTranDeptAfter());
            }
            //处理下部门
            if(!StringUtils.checkNull(hrTransferWithBLOBs.getTranDeptBefore())){
                dept = hrTransferWithBLOBs.getTranDeptBefore().split(",");
                for(String  hr : dept){
                    String deptName=departmentMapper.getDeptNameById(Integer.parseInt(hr));
                    deptBefore += deptName+",";
                }
                hrTransferWithBLOBs.setTranDeptBefore(deptBefore);
            }
            if(!StringUtils.checkNull(hrTransferWithBLOBs.getTranDeptAfter())){
                dept = hrTransferWithBLOBs.getTranDeptAfter().split(",");
                for(String  hr : dept){
                    String deptName=departmentMapper.getDeptNameById(Integer.parseInt(hr));
                    deptBefores += deptName+",";
                }
                hrTransferWithBLOBs.setTranDeptAfter(deptBefores);
            }
            String name="";
            if(hrTransferWithBLOBs !=null){
                if(hrTransferWithBLOBs.getTransferPerson()!=null){
                   String ids[]= hrTransferWithBLOBs.getTransferPerson().split(",");
                   for(String id:ids){
                       name+= usersMapper.getUsernameByUserId(id)+",";
                   }
                }
                hrTransferWithBLOBs.setTransferPersonName(name);
                //附件处理
                List<Attachment> attachmentList=GetAttachmentListUtil.returnAttachment(hrTransferWithBLOBs.getAttachmentName(),hrTransferWithBLOBs.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), "sdas");
                hrTransferWithBLOBs.setAttachmentList(attachmentList);
                json.setObject(hrTransferWithBLOBs);
                json.setFlag(0);
                json.setMsg("详情查询成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }
    /**
     * @author 程叶同
     * @date 2018/7/23 16:33
     * @desc  人力资源系统代码表
     */
    private static final String HR_SCHOOL="HR_STAFF_TRANSFER";
    public BaseWrapper getHrCodes(String type){
        BaseWrapper baseWrapper=new BaseWrapper();
        List<HrCode> hrCodes=new ArrayList<>();
        HrCodeExample hrCodeExample=new HrCodeExample();
        HrCodeExample.Criteria criteria = hrCodeExample.createCriteria();
        hrCodeExample.setOrderByClause("cast(CODE_NO as SIGNED INTEGER) ASC");
        if ("edu".equals(type)) { //获取调动类型
            criteria.andParentNoEqualTo(HR_SCHOOL);
            hrCodes = hrCodeMapper.selectByExampleWithBLOBs(hrCodeExample);
        }
        baseWrapper.setMsg("ok");
        baseWrapper.setFlag(true);
        baseWrapper.setData(hrCodes);
        baseWrapper.setStatus(true);
        return  baseWrapper;
    }

    /**
     * 导入
     */
    @SuppressWarnings("all")
    public ToJson<HrTransferWithBLOBs> importsHrTransfer(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        ToJson<HrTransferWithBLOBs> json = new ToJson<HrTransferWithBLOBs>(1,"error");
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
             StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                path = path.append(str2 + "/xoa");
            }
            path.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            path=path.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }

            int success=0;
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    HrTransferWithBLOBs hrTransferWithBLOBs = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        hrTransferWithBLOBs = new HrTransferWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            // 用户名
                                            Users users = usersMapper.getUserByUserName(cell.getStringCellValue());
//                                            Department department = departmentMapper.getDeptById(users.getDeptId());
                                            hrTransferWithBLOBs.setCreateUserId(cell.getStringCellValue());
//                                            hrphotoWithBLOBs.setCreateDeptId(department.getDeptId());
                                            break;
                                        case 1:
                                            // 调动人员
                                            if (cell.getStringCellValue() != null) {
                                                Users user = usersMapper.getUserByUserName(cell.getStringCellValue());
                                                hrTransferWithBLOBs.setTransferPerson(user.getUserId());
                                            }
                                            break;
                                        case 2:
                                            //调动类型
                                            hrTransferWithBLOBs.setTransferType(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //调动日期
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrTransferWithBLOBs.setTransferDate(date);
                                                break;
                                            }
                                            hrTransferWithBLOBs.setTransferDate(DateFormat.getDate(cell.getStringCellValue()));
                                            break;
                                        case 4:
                                            //调动生效日期
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrTransferWithBLOBs.setTransferEffectiveDate(date);
                                                break;
                                            }
                                            hrTransferWithBLOBs.setTransferEffectiveDate(DateFormat.getDate(cell.getStringCellValue()));
                                            break;
                                        case 5:
                                            // 调动前单位
                                            hrTransferWithBLOBs.setTranCompanyBefore(cell.getStringCellValue());
                                            break;
                                        case 6:
                                            // 调动后单位
                                            hrTransferWithBLOBs.setTranCompanyAfter(cell.getStringCellValue());
                                            break;
                                        case 7:
                                            // 调动前部门
                                            hrTransferWithBLOBs.setTranDeptBefore(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            //调动后部门
                                            hrTransferWithBLOBs.setTranDeptAfter(cell.getStringCellValue());
                                            break;
                                        case 9:
                                            // 调动前职务
                                            hrTransferWithBLOBs.setTranPositionBefore(cell.getStringCellValue());
                                            break;
                                        case 10:
                                            // 调动后职务
                                            hrTransferWithBLOBs.setTranPositionAfter(cell.getStringCellValue());
                                            break;
                                        case 11:
                                            // 调动手续办理
                                            hrTransferWithBLOBs.setMaterialsCondition(cell.getStringCellValue());
                                            break;
                                        case 12:
                                            // 调动原因
                                            hrTransferWithBLOBs.setTranReason(cell.getStringCellValue());
                                            break;
                                        case 13:
                                            // 备注
                                            hrTransferWithBLOBs.setRemark(cell.getStringCellValue());
                                            break;
                                    }

                                }
                            }
                            if(hrTransferWithBLOBs!=null){
                                hrTransferWithBLOBs.setAddTime(new Date());
                                hrTransferWithBLOBs.setLastUpdateTime(new Date());
                                Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
                                Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
                                //创建者用户名
                                hrTransferWithBLOBs.setCreateUserId(user.getUserId());
                                //创建者部门编号
                                hrTransferWithBLOBs.setCreateDeptId(user.getDeptId());
                                //批示
                                if(StringUtils.checkNull(hrTransferWithBLOBs.getDespacho())){
                                    hrTransferWithBLOBs.setDespacho("");
                                }
                                //调动手续办理
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getMaterialsCondition())){
                                    hrTransferWithBLOBs.setMaterialsCondition("");
                                }
                                //附件名称
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getAttachmentName())){
                                    hrTransferWithBLOBs.setAttachmentName("");
                                }
                                //附件ID
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getAttachmentId())){
                                    hrTransferWithBLOBs.setAttachmentId("");
                                }
                                //备注
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getRemark())){
                                    hrTransferWithBLOBs.setRemark("");
                                }
                                //经办人
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getResponsiblePerson())){
                                    hrTransferWithBLOBs.setResponsiblePerson("");
                                }
                                //调动类别
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getTransferType())){
                                    hrTransferWithBLOBs.setTransferType("");
                                }
                                //调动原因
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getTranReason())){
                                    hrTransferWithBLOBs.setTranReason("");
                                }
                                //调动前单位
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getTranCompanyBefore())){
                                    hrTransferWithBLOBs.setTranCompanyBefore(" ");
                                }
                                //调动前部门
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getTranDeptBefore())){
                                    hrTransferWithBLOBs.setTranDeptBefore(" ");
                                }
                                //调动前职务
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getTranPositionBefore())){
                                    hrTransferWithBLOBs.setTranPositionBefore(" ");
                                }
                                //调动后单位
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getTranCompanyAfter())){
                                    hrTransferWithBLOBs.setTranCompanyAfter(" ");
                                }
                                //调动后部门
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getTranDeptAfter())){
                                    hrTransferWithBLOBs.setTranDeptAfter(" ");
                                }
                                //调动后职务
                                if (StringUtils.checkNull(hrTransferWithBLOBs.getTranPositionAfter())){
                                    hrTransferWithBLOBs.setTranPositionAfter(" ");
                                }
                                //添加日期转换
                                if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferDates())){
                                    hrTransferWithBLOBs.setTransferDate(DateFormat.getDates(hrTransferWithBLOBs.getTransferDates()));
                                }
                                //添加日期转换
                                if (!StringUtils.checkNull(hrTransferWithBLOBs.getTransferEffectiveDates())){
                                    hrTransferWithBLOBs.setTransferEffectiveDate(DateFormat.getDates(hrTransferWithBLOBs.getTransferEffectiveDates()));
                                }

                            }

                        }
                    }
                }

            }
            HrphotoWithBLOBs temp=new HrphotoWithBLOBs();
            temp.setCount(success);
            json.setFlag(0);
            json.setMsg("ok");
            json.setObject(temp);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("数据保存异常");
            json.setFlag(1);
        }
        return json;
    }

    public List<HrTransferWithBLOBs> getUserName(String userId){
        List<HrTransferWithBLOBs> list = hrTransferMapper.getHrStaffContractList(userId);
        String[] dept ;
        String deptBefore="";
        String[] dept1 ;
        String deptBefore1="";

        //处理姓名
        for (HrTransferWithBLOBs  hr :list){
            String transferPerson = hr.getTransferPerson();
            //员工姓名
            if (transferPerson.contains(",")) {
                String substring = transferPerson.substring(0, transferPerson.length() - 1);
                hr.setTransferPerson(substring);
            }
            String username = usersMapper.getUsernameByUserId(hr.getTransferPerson());
            hr.setTransferPerson(username);
            //处理部门
            if(!StringUtils.checkNull(hr.getTranDeptBefore())){
                dept = hr.getTranDeptBefore().split(",");
                for(String  hr1 : dept){
                    String deptName=departmentMapper.getDeptNameById(Integer.parseInt(hr1));
                    deptBefore += deptName+",";
                }
                hr.setTranDeptBefore(deptBefore);
            }
            if(!StringUtils.checkNull(hr.getTranDeptAfter())){
                dept1 = hr.getTranDeptAfter().split(",");
                for(String  hr2 : dept1){
                    String deptName=departmentMapper.getDeptNameById(Integer.parseInt(hr2));
                    deptBefore1 += deptName+",";
                }
                hr.setTranDeptAfter(deptBefore1);
            }
            switch(hr.getTransferType()){
                case"1":
                    hr.setTransferType("晋升");
                    break;
                case "2":
                    hr.setTransferType("平调");
                    break;
                case"3":
                    hr.setTransferType("降级");
                    break;
                case "4":
                    hr.setTransferType("其他");
                    break;
            }
        }
        return list;
    }

    /**
     * 创建者：戚中校
     * 方法作用：人事分析人事调动信息数量查询
     * @param
     * @return
     */
    public ToJson<HrTransfer> selectNumByCon(HrTransfer record, Integer[] deptId){
        ToJson toJson = new ToJson();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (deptId != null && deptId.length > 0){
                map.put("deptId",deptId);
            }
            map.put("record",record);
            List<HrTransfer> list = hrTransferMapper.selectNumByCon(map);

            for (HrTransfer hrTransfer : list){
                if(hrTransfer.getTransferType() != null){
                    switch(hrTransfer.getTransferType()){
                        case"1":
                            hrTransfer.setTransferType("晋升");
                            break;
                        case "2":
                            hrTransfer.setTransferType("平调");
                            break;
                        case"3":
                            hrTransfer.setTransferType("降级");
                            break;
                        case "4":
                            hrTransfer.setTransferType("其他");
                            break;
                    }
                }
            }
            if(list.size() >= 0){
                toJson.setObj(list);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }

        }catch (Exception e){
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }
    public ToJson<HrTransferWithBLOBs> getByStaffName(String staffName, Integer page, Integer pageSize, boolean useFlag){
        ToJson<HrTransferWithBLOBs> json = new ToJson<HrTransferWithBLOBs>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        HashMap<String,Object> map = new HashMap();
        map.put("pageParams", pageParams);
        map.put("staffName",staffName);
        try{
            List<HrTransferWithBLOBs> list=hrTransferMapper.getByStaffName(map);
            if(list.size()>0){
                for(HrTransferWithBLOBs tran:list){
                    if(tran.getTransferPerson()!=null){
                        Users user = usersMapper.findUsersByuserId(tran.getTransferPerson()); //根据 id 找名字
                        tran.setTransferPersonName(user.getUserName());
                    }
                    //调动类型
                    HrCode hr_staff_contract2 = hrCodeMapper.selectCode("HR_STAFF_TRANSFER",tran.getTransferType());
                    if (hr_staff_contract2 != null) {
                        tran.setTransferType(hr_staff_contract2.getCodeName());
                    } else {
                        tran.setTransferType(" ");
                    }
                }
                json.setObj(list);
            }
            json.setTotleNum(hrTransferMapper.getByStaffNameCount(staffName));
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception E){
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }
}
